﻿#ifndef KNN_H
#define KNN_H
#include<iostream>
#include<map>
#include<vector>
#include<stdio.h>
#include<cmath>
#include<algorithm>
#include<fstream>
#include<cstdlib>

using namespace std;

#define maxRow 12
#define maxCol 2

typedef pair<int, double> PAIR;

ifstream fin;

class KNN
{
private:
    int k;
    double dataSet[maxRow][maxCol];
    char   labels[maxRow];
    double testData[maxCol];
    map<int, double> map_index_dis;
    map<char, int> map_label;
    double get_distance(double* dt1, double* dt2);
public:
    KNN();
    void get_all_distance();
    char get_max_fre_label();
    void knn_input(float x,float y);
    void show();
    struct CmpByValue
    {
        bool operator() (const PAIR& lhs, const PAIR& rhs)
        {
            return lhs.second < rhs.second;
        }

    };

};
void KNN::show()
{
    map<int, double>::iterator it;
    for (it = map_index_dis.begin(); it != map_index_dis.end(); it++)
    {
        cout << "index = " << it->first << "  value = " << it->second << endl;
    }


}
KNN::KNN()
{

    if (!fin)
    {
        cout << "can nod load the file" << endl;;
        system("pause");
        exit(1);
    }
    for (int i = 0; i < maxRow; i++)
    {
        for (int j = 0; j < maxCol; j++)
        {
            fin >> dataSet[i][j];
        }
        fin >> labels[i];
    }


}
double KNN::get_distance(double* dt1, double* dt2)
{
    double sum = 0;
    for (int i = 0; i < maxCol; i++)
    {
        sum += pow((dt1[i] - dt2[i]), 2);
    }
    return (sqrt(sum));
}
void KNN::get_all_distance()
{
    double distance;

    for (int i = 0; i < maxRow; i++)
    {
        distance = get_distance(dataSet[i], testData);
        map_index_dis[i] = distance;
    }


}

char KNN::get_max_fre_label()
{
    vector<pair<int, double>> vec_index_dis(map_index_dis.begin(), map_index_dis.end());
    sort(vec_index_dis.begin(), vec_index_dis.end(), CmpByValue());
    cout << "前" << k << "个最小数据排序为:" << endl;
    for (int i = 0; i < k; i++)
    {
        cout << "index = " << vec_index_dis[i].first << " the distance= " << vec_index_dis[i].second
            << " the label = " << labels[vec_index_dis[i].first]
            << " the coordinate(" << dataSet[vec_index_dis[i].first][0] << ","
            << dataSet[vec_index_dis[i].first][0] << ")" << endl;

        map_label[labels[vec_index_dis[i].first]]++;
    }
    map<char, int>::iterator itr = map_label.begin();
    int max_freq = 0;
    char label;
    while (itr != map_label.end())
    {
        if (itr->second > max_freq)
        {
            max_freq = itr->second;
            label = itr->first;
        }
        itr++;
    }
    cout << "数据属于标签：" << endl;
    cout << "label = " << label << endl;
    return label;
}
void KNN::knn_input(float x,float y)
{
    testData[0]=x;
    testData[1]=y;
    k=1;
}
#endif // KNN_H
